package cn.itsource.ymcc.web.controller;

import cn.itsource.ymcc.config.AliPayConfig;
import cn.itsource.ymcc.dto.AlipayNotifyDto;
import cn.itsource.ymcc.service.IPayOrderService;
import cn.itsource.ymcc.domain.PayOrder;
import cn.itsource.ymcc.query.PayOrderQuery;
import cn.itsource.ymcc.result.JsonResult;
import cn.itsource.ymcc.result.PageList;
import cn.itsource.ymcc.vo.PayVo;
import com.alipay.easysdk.factory.Factory;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
@RestController
@RequestMapping("/payOrder")
public class PayOrderController {

    @Autowired
    public IPayOrderService payOrderService;

    @Autowired
    private AliPayConfig aliPayConfig;

    //        parameterMap.forEach((k,v)->{
//            System.out.print(k+":");//map里面的key值
//            System.out.println(v[0]);//map的对应value值
//        });

    @PostMapping("/asyncNotify")
    public String asyncNotify(HttpServletRequest request){
        //这个是转换后的值
        Map<String, String> parameter = new HashMap<>();
        try {
            //这个方法可以得到所有的请求参数
            Map<String, String[]> parameterMap = request.getParameterMap();

            Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
            for (Map.Entry<String, String[]> entry : entries) {
                parameter.put(entry.getKey(),entry.getValue()[0]);
            }

            System.out.println(parameter.get("total_amount"));

            //发送请求到支付宝进行二次验签
            Boolean aBoolean = aliPayConfig.verifyNotify(parameter);
            if(aBoolean){//true 验签成功
                payOrderService.asyncNotify(parameter);
            }else {
                System.out.println("返回的是failure");
                //还可以记录到数据库里面去
                return "failure";
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error("支付宝二次验签失败,订单号为:",parameter.get("out_trade_no"));
            //还可以记录到数据库里面去
            e.printStackTrace();
        }

        return "success";
    }

    @PostMapping("/apply")
    public JsonResult apply(@RequestBody @Valid PayVo payVo){
        return payOrderService.apply(payVo);
    }

    @GetMapping("/checkPayOrder/{orderNo}")
    public JsonResult checkPayOrder(@PathVariable("orderNo")String orderNo){
        PayOrder one = payOrderService.getOne(new LambdaQueryWrapper<PayOrder>().eq(PayOrder::getOrderNo, orderNo));
        return  one==null?JsonResult.error("支付单未生成"):JsonResult.success().setData(orderNo);
    }

    /**
    * 保存和修改公用的
    */
    @PostMapping("/save")
    public JsonResult saveOrUpdate(@RequestBody PayOrder payOrder){
        if(payOrder.getId()!=null){
            payOrderService.updateById(payOrder);
        }else{
            payOrderService.save(payOrder);
        }
        return JsonResult.success();
    }

    /**
    * 删除对象
    */
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long id){
        payOrderService.removeById(id);
        return JsonResult.success();
    }

    /**
   * 获取对象
   */
    @GetMapping("/{id}")
    public JsonResult get(@PathVariable("id")Long id){
        return JsonResult.success().setData(payOrderService.getById(id));
    }


    /**
    * 查询所有对象
    */
    @GetMapping("/list")
    public JsonResult list(){
        return JsonResult.success().setData(payOrderService.list(null));
    }


    /**
    * 带条件分页查询数据
    */
    @PostMapping("/pagelist")
    public JsonResult page(@RequestBody PayOrderQuery query){
        Page<PayOrder> page = new Page<PayOrder>(query.getPageNo(), query.getPageSize());
        page = payOrderService.page(page);
        return JsonResult.success().setData(new PageList<PayOrder>(page.getTotal(), page.getRecords()));
    }
}
